<template>
    <div>
        <div id="s_index">
            <div class="header "><span>已获取积分：{{data.coin}}</span><span>客服:{{phone}}</span></div>
            <div class="concern" v-if="qrcode.length!=0">
                <div class="border-img">
                    <swiper :options="swiperOption" ref="mySwiper">
                        <swiper-slide v-for="(item,index) in qrcode" :key="index">
                            <img :src="item.qrcodeUrl" :data-appid="item.appid">
                        </swiper-slide>
                        <div class="swiper-pagination" slot="pagination"></div>
                        <div class="swiper-button-prev" slot="button-prev"></div>
                        <div class="swiper-button-next" slot="button-next"></div>
                    </swiper>
                </div>
                <span class="ten">长按关注公众号回复<span class="font-red">888</span>免费领取积分</span>
            </div>
            <div class="concern" v-else>
                <div class="title">充值后,点击出货启动设备</div>
                <!--<div class="title">充值后,点击出货启动设备</div>-->
            </div>
            <div class="game clearfix" @click="goGame()" v-if="gameStatus">
                <img src="../../static/img/wawa.jpg" width="90px" alt="" style="border-bottom-left-radius: 6px;border-top-left-radius: 6px" class="fl">
                <div class="fl game_title">
                    <p>抓娃娃</p>
                    <small>玩游戏，赢积分，赚大礼！</small>
                </div>
            </div>
            <div class="buttons clearfix">
                <div class="pay" @click.prevent="tan()">
                    支付购买积分
                </div>
                <div class="goods" @click.prevent="chage(1)">
                    出货({{price}}积分/个)
                </div>
            </div>
        </div>
        <transition :duration="300" name="fade" v-on:leave="leave">
            <div class="overlay" v-show="statu">
                <div class="show_head" @click.prevent.stop="statu=false">
                </div>
                <div class="lightbox" v-show="statu2">
                    <div class="lightbox_title">支付购买积分</div>
                    <div class="lightbox_money">
                        <p>支付金额</p>
                        <div class="money" v-for="item in money" @click.stop="pay(item.money)" v-show="statu">
                            <p>{{item.money}}.00元 </p>
                            <p>{{item.num}}个积分</p>
                        </div>
                    </div>
                    <div><span>若支付失败30分钟内自动返回微信钱包</span></div>
                </div>
            </div>
        </transition>
        <transition :duration="300" name="fade" v-on:click="leave">
            <div class="overlay" v-show="goodsStatu">
                <div class="show_head" @click.prevent.stop="leave">
                    {{test}}
                </div>
                <div class="lightbox" v-show="goodsStatu2">
                    <div class="lightbox_title title_background">积分兑换商品</div>
                    <div class="lightbox_money lightbox_coin">
                        <p class="p">提示：绑定设备成功后点击设备出货，每次仅能出一个货物</p>
                        <!--<div class="money" v-for="item in shopChange" @click.stop="contentDevice(item.num)">-->
                        <!--<p>{{item.num}}个积分 </p>-->
                        <!--<p>{{item.shop}}个商品</p>-->
                        <!--</div>-->
                        <button class="buttons2" @click="binding()">绑定设备</button>
                        <img src="../../static/img/arrow_right.png" alt="" style="vertical-align: middle">
                        <button class="buttons2" @click="content()">出货</button>
                    </div>
                    <div><span>若出货失败10分钟内积分会自动返回</span></div>
                </div>
            </div>
        </transition>
        <div class="popup" v-show="running">
            <div id="progress" style="">
                <svg viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg"
                     xmlns:xlink="http://www.w3.org/1999/xlink">
                    <g id="circle" class="g-circles g-circles--v1">
                        <circle id="12" transform="translate(35, 16.698730) rotate(-30) translate(-35, -16.698730) "
                                cx="35"
                                cy="16.6987298" r="10"></circle>
                        <circle id="11" transform="translate(16.698730, 35) rotate(-60) translate(-16.698730, -35) "
                                cx="16.6987298"
                                cy="35" r="10"></circle>
                        <circle id="10" transform="translate(10, 60) rotate(-90) translate(-10, -60) " cx="10" cy="60"
                                r="10"></circle>
                        <circle id="9" transform="translate(16.698730, 85) rotate(-120) translate(-16.698730, -85) "
                                cx="16.6987298"
                                cy="85" r="10"></circle>
                        <circle id="8" transform="translate(35, 103.301270) rotate(-150) translate(-35, -103.301270) "
                                cx="35"
                                cy="103.30127" r="10"></circle>
                        <circle id="7" cx="60" cy="110" r="10"></circle>
                        <circle id="6" transform="translate(85, 103.301270) rotate(-30) translate(-85, -103.301270) "
                                cx="85"
                                cy="103.30127" r="10"></circle>
                        <circle id="5" transform="translate(103.301270, 85) rotate(-60) translate(-103.301270, -85) "
                                cx="103.30127"
                                cy="85" r="10"></circle>
                        <circle id="4" transform="translate(110, 60) rotate(-90) translate(-110, -60) " cx="110" cy="60"
                                r="10"></circle>
                        <circle id="3" transform="translate(103.301270, 35) rotate(-120) translate(-103.301270, -35) "
                                cx="103.30127" cy="35" r="10"></circle>
                        <circle id="2" transform="translate(85, 16.698730) rotate(-150) translate(-85, -16.698730) "
                                cx="85"
                                cy="16.6987298" r="10"></circle>
                        <circle id="1" cx="60" cy="10" r="10"></circle>
                    </g>
                    <use xlink:href="#circle" class="use"/>
                </svg>
                <div class="font-status">{{contentStatus}}</div>
            </div>
        </div>

    </div>

</template>

<script>

    import Vue from 'vue'

    import VueAwesomeSwiper from 'vue-awesome-swiper'

    Vue.use(VueAwesomeSwiper)

    import {swiper, swiperSlide} from 'vue-awesome-swiper'

    import Vuwe from 'vuwe'

    Vue.use(Vuwe)

    import VueResource from 'vue-resource'

    Vue.use(VueResource)

    import jw from '../../node_modules/jquery-weui/dist/js/jquery-weui.min.js'

    var VueTouch = require('vue-touch');
    Vue.use(VueTouch, {name: 'v-touch'});

    function GetRequest(strName) {
        var strHref = window.location.href
        var intPos = strHref.indexOf("?");
        var strRight = strHref.substr(intPos + 1);
        var arrTmp = strRight.split("&");
        for (var i = 0; i < arrTmp.length; i++) {
            var arrTemp = arrTmp[i].split("=")
            if (arrTemp[0].toUpperCase() == strName.toUpperCase()) {
                return arrTemp[1]
            }
        }
        return '9';
    }

    var timeout;

    export default {
        components: {
            swiper,
            swiperSlide
        },
        data() {
            return {
                swiperOption: {
                    pagination: '.swiper-pagination',
                    nextButton: '.swiper-button-next',
                    prevButton: '.swiper-button-prev',
                    slidesPerView: 1,
                    paginationClickable: true,
                    spaceBetween: 30,
                    loop: true
                },
                status: false,
                show: true,
                statu: false,
                statu2: false,
                goodsStatu: false,
                goodsStatu2: false,
                gameStatus:false,
                money: [
                    {
                        money: 1,
                        num: 1
                    },
                    {
                        money: 2,
                        num: 2
                    },
                    {
                        money: 3,
                        num: 3
                    },
                    {
                        money: 4,
                        num: 4
                    },
                    {
                        money: 5,
                        num: 5
                    },
                    {
                        money: 6,
                        num: 6
                    },
                    {
                        money: 7,
                        num: 7
                    },
                    {
                        money: 8,
                        num: 8
                    },
                    {
                        money: 9,
                        num: 9
                    }
                ],
                running: false,
                deviceId: '',
                test: '',
                price: '',
                data: {
                    coin: 0,
                },
                phone: 13794181215,
                qrcode: [
                    {
                        appid: "wxe269be5d7e65716d",
                        qrcodeUrl: '../../static/img/loading.png',
                        WOA: "趣扫扫"
                    },
                ],
                contentStatus: "稍等片刻，连接设备中"
            }
        },
        methods: {
            tan() {
                this.statu = true;
                this.statu2 = true;
            },
            chage(num) {
                if (this.data.coin < num) {
                    $.toptip('您的积分不够，快去关注公众号领取免费积分！', 2200, 'warning')
                } else {
                this.goodsStatu = true;
                this.goodsStatu2 = true;
                }
            },
            binding() {
                const self = this;
                self.running = true;
                self.contentStatus = "稍等片刻，绑定设备中..."
                const eid = localStorage.getItem('eid')
                const deviceid = 'gh_5a4732cdef76_' + eid
//                self.goodsStatu2 = false;
//                wx.ready(function () {
                //1.打开微信设备库
                wx.invoke('openWXDeviceLib', {'brandUserName': 'gh_5a4732cdef76'}, function (res) {
                })
                wx.invoke('getWXDeviceTicket', {
                    'deviceId': deviceid,
                    type: 1,
                    'connType': 'blue'
                }, function (res) {
                    self.$http.post('/api/v1/hardware/bind/', {eid: eid, ticket: res.ticket})
                        .then((res) => {
                            if (res.data.code == '1') {
                                $.toptip('设备绑定成功，请点击出货！', 1500, 'success')
                                self.running = false;
                            } else {
                                $.toptip('设备绑定失败，请重新点击出货', 1500, 'error')
                                self.running = false;
                            }
                            wx.invoke('disconnectWXDevice', {
                                'deviceId': deviceid,
                                'connType': 'blue'
                            }, function (res) {
                            })
                            wx.invoke('closeWXDeviceLib', {
                                'deviceId': deviceid,
                                'connType': 'blue'
                            }, function (res) {
                            })
                        }).catch((err) => {
                    })
                })
                wx.error(function (res) {
                    self.goodsStatu = false;
                    self.running = false;
                    alert("连接错误，请重新连接！");
                });
//                })
            },
//            连接设备。
            content() {
                const self = this;
                self.running = true;
                self.contentStatus = "稍等片刻，连接设备中"
                const eid = localStorage.getItem('eid')
                const deviceid = 'gh_5a4732cdef76_' + eid
                self.goodsStatu2 = false;
                wx.ready(function () {
                    wx.invoke('disconnectWXDevice', {
                        'deviceId': deviceid,
                        'connType': 'blue'
                    }, function (res) {
                    })
                    wx.invoke('closeWXDeviceLib', {
                        'deviceId': deviceid,
                        'connType': 'blue'
                    }, function (res) {
                    })
                    //1.打开微信设备库
                    wx.invoke('openWXDeviceLib', {'brandUserName': 'gh_5a4732cdef76'}, function (res) {
                        if (res.err_msg == 'openWXDeviceLib:ok') {
                            if (res.bluetoothState == 'off') {
                                self.running = false;
                                self.goodsStatu = false;
                                alert("使用前请先打开手机蓝牙")
                            } else if (res.bluetoothState == 'unauthorized') {
                                self.running = false;
                                self.goodsStatu = false;
                                alert("请授权微信蓝牙功能并打开蓝牙")
                            } else if (res.bluetoothState == 'on') {
                            }
                        } else {
                            self.goodsStatu = false;
                            alert("请授权微信蓝牙功能并打开蓝牙")
                        }
                    })
                    //2.3 手机蓝牙状态改变事件
                    wx.on('onWXDeviceBluetoothStateChange', function (argv) {
                        if (argv.bluetoothState == 'unauthorized') {
                            $.toptip('请打开蓝牙连接设备', 1500, 'error')
                        }
                    });
                    //2.4 安装监听设备连接状态事件
                    wx.on('onWXDeviceStateChange', function (res) {
                        if (res.state == "connecting") {
                            self.contentStatus = "正在连接"
                        } else if (res.state == "connected") {
                            // 发送信息
                            self.contentStatus = "连接成功"
                            self.$http.post('/api/v1/hardware/sale/', {eid: eid, passage: self.$route.params.name})
                                .then((res) => {
//                                    $.toptip(res.data.msg, 1500, 'success')
                                    if (res.data.code == 1) {
                                        self.running = false;
                                        self.goodsStatu = false;
                                        $.toptip('出货成功', 1500, 'success')
                                        wx.invoke('disconnectWXDevice', {
                                            'deviceId': deviceid,
                                            'connType': 'blue'
                                        }, function (res) {
                                        })
                                        wx.invoke('closeWXDeviceLib', {
                                            'deviceId': deviceid,
                                            'connType': 'blue'
                                        }, function (res) {
                                        })
                                    } else {
                                        self.running = false
                                        self.goodsStatu = false;
                                        $.toptip('出货失败，请重新尝试', 1500, 'error')
                                    }
                                }, function (err) {
                                    self.running = false;
                                    self.goodsStatu = false;
                                    $.toptip(err.data.msg, 1500, 'error')
                                })
                        } else if (res.state == "disconnected") {
                            self.contentStatus = "断开连接"
                        }
                    })
                    //3.刷新设备信息
                    wx.invoke('connectWXDevice', {
                        'deviceId': deviceid,
                        'connType': 'blue'
                    }, function (res) {
                        if (res.err_msg == "connectWXDevice:ok") {
                        } else {
                            self.running = false;
                            self.goodsStatu = false;
                            alert("连接失败，请重新连接")
                        }
                    })
                    wx.error(function (res) {
                        self.goodsStatu = false;
                        self.running = false;
                        $.toptip("连接错误，请重新连接！", 1500, 'warning')
                    });
                })
            },
            //下单并调起支付
            pay(money) {
                var eid = localStorage.getItem("eid")
                //var openid = localStorage.getItem("openid")
                var obj = {device_info: eid, total_fee: money}
                var self = this;
                this.$http.post('/api/v1/wxpay/create_order/', obj)
                    .then((res) => {
                        wx.chooseWXPay({
                            timestamp: res.data.timestamp,
                            nonceStr: res.data.nonceStr,
                            package: res.data.package,
                            signType: 'MD5',
                            paySign: res.data.paySign,
                            success: function (res) {
                                alert(res.errMsg);
                                if (res.errMsg == "chooseWXPay:ok") {
                                    self.$http.get('/api/v1/wechat/qrcode/' + eid)
                                        .then(function (res) {
                                            alert(res.data.data.coin)
                                            if (res.data.data.coin == '' || res.data.data.coin == undefined) {
                                                this.data.coin = 0;
                                            } else {
                                                this.data = res.data.data;
                                            }
                                        }, function (err) {
                                            console.log(err)
                                        })
                                }
                            }
                        })
                    }).catch((err) => {
                    console.error(err)
                })
            },
            leave() {
                console.log(this.running)
                if (this.running) {
                } else {
                    this.statu2 = false;
                    this.goodsStatu = false;
                    this.goodsStatu2 = false;
                }
            },
            goGame(){
                window.location.href = 'http://www.nowdone.com.cn/claw/'
            }
        },
        mounted() {
            var timeOutEvent;
            var self = this;
//            长按方法
            var mySwiper = new Swiper('.swiper-container', {
                onTouchStart: function (swiper, ev) {
//                    ev.preventDefault();
                    const appid = ev.srcElement.dataset.appid;
                    timeOutEvent = setTimeout(function () {
                        timeOutEvent = 0;
                        self.$http.post('/api/v1/coin/create_token/', {appid: appid})
                            .then(function (res) {
                                if (res.data.code == '1') {
                                    localStorage.setItem("token", res.data.token);
                                } else {
                                    this.status = "ture";
                                }
                            }, function (err) {
                                console.log(err)
                            })
                    }, 500);
                },
                onTouchMove: function (swiper) {
                    clearTimeout(timeOutEvent);
                    timeOutEvent = 0;
                },
                onTouchEnd: function (swiper, ev) {
                    clearTimeout(timeOutEvent);
                }
            })
            var innerHeight = window.innerHeight;
            $('body').css('height', innerHeight + 'px');
            $('.concern').css('height', (innerHeight + 50 ) / 2 + 'px');
            const eid = localStorage.getItem('eid');

            var img = $("img")
            this.$http.get('/api/v1/wechat/qrcode/' + eid + '/' + this.$route.params.name)
                .then(function (res) {
                    if (res.data.data.coin == '' || res.data.data.coin == undefined) {
                        this.data.coin = 0;
                    } else {
                        this.data = res.data.data;
                    }
                    this.gameStatus = res.data.data.activityState;
                    this.qrcode = res.data.data.qrcode;
                    this.price = res.data.data.price;
                }, function (err) {
                    console.log(err)
                })
            const url = encodeURIComponent(window.location.href)
            this.$http.get('/api/v1/sdk/get_jssdk_signature/?url=' + url)
                .then((res) => {
                    wx.config({
                        beta: true,
                        debug: false,
                        appId: 'wxe269be5d7e65716d',
                        timestamp: res.data.timestamp,
                        nonceStr: res.data.noncestr,
                        signature: res.data.signature,
                        jsApiList: [
                            'chooseWXPay',//调用支付
                            'openWXDeviceLib',//初始化设备库（只支持蓝牙设备）
                            'closeWXDeviceLib',//关闭设备库（只支持蓝牙设备）
                            'getWXDeviceInfos',//获取设备信息（获取当前用户已绑定的蓝牙设备列表）
                            'sendDataToWXDevice',//发送数据给设备
                            'startScanWXDevice',//扫描设备（获取周围所有的设备列表，无论绑定还是未被绑定的设备都会扫描到）
                            'stopScanWXDevice',//停止扫描设备
                            'connectWXDevice',//连接设备
                            'disconnectWXDevice',//断开设备连接
                            'getWXDeviceTicket',//获取操作凭证
                            'onWXDeviceBindStateChange',//微信客户端设备绑定状态被改变时触发此事件
                            'onWXDeviceStateChange',//监听连接状态，可以监听连接中、连接上、连接断开
                            'onReceiveDataFromWXDevice',//接收到来自设备的数据时触发
                            'onScanWXDeviceResult',//扫描到某个设备时触发
                            'onWXDeviceBluetoothStateChange',//手机蓝牙打开或关闭时触发
                        ]
                    })
                    wx.error(function (res) {
                        alert("wx错误：" + JSON.stringify(res));
                        //如果初始化出错了会调用此方法，没什么特别要注意的
                    });
                }).catch((err) => {
                console.error(err)
            })
        }
    }
</script>

<style lang="less">
    @import '../less/s_index.less';
</style>